import logging
from QQLoginTool.QQtool import OAuthQQ
from django import http
from django.contrib.auth import login
from django.http import JsonResponse
from django.shortcuts import render, redirect

# Create your views here.
from django.urls import reverse
from django.views import View

from apps.oauth.models import OAuthQQUser, OAuthSinaUser
from apps.oauth.utils import generate_safe_openid, load_true_openid
from apps.users.models import User
from libs import sinaweibopy3
from meiduo_mall_chen import settings
from utils.response_code import RETCODE


class QQAuthView(View):
    def get(self, request):
        oauth = OAuthQQ(client_id=settings.QQ_CLIENT_ID,
                        client_secret=settings.QQ_CLIENT_SECRET,
                        redirect_uri=settings.QQ_REDIRECT_URI,
                        state='test')
        login_url = oauth.get_qq_url()

        return JsonResponse({'login_url': login_url})


class Auth_CallbackView(View):
    def get(self, request):
        code = request.GET.get('code')
        if code is None:
            return http.HttpResponseBadRequest('参数不全')
        auth = OAuthQQ(client_id=settings.QQ_CLIENT_ID,
                       client_secret=settings.QQ_CLIENT_SECRET,
                       redirect_uri=settings.QQ_REDIRECT_URI,
                       state='test')
        token = auth.get_access_token(code)
        true_openid = auth.get_open_id(token)
        # return render(request,'oauth_callback.html')
        try:
            qquser = OAuthQQUser.objects.get(openid=true_openid)
        except OAuthQQUser.DoesNotExist:
            openid = generate_safe_openid(true_openid).decode()
            return render(request, 'oauth_callback.html', context={'openid': openid})
        else:
            login(request, qquser.user)
            response = redirect(reverse('contents:index'))
            response.set_cookie('username', qquser.user.username)
        return response

    def post(self, request):
        mobile = request.POST.get('mobile')
        password = request.POST.get('pwd')
        sms_code = request.POST.get('sms_code')
        img_code = request.POST.get('pic_code')
        safe_openid = request.POST.get('openid').encode()
        openid = load_true_openid(safe_openid)

        try:
            user = User.objects.get(mobile=mobile)
        except User.DoesNotExist:
            user = User.objects.create_user(
                username=mobile,
                mobile=mobile,
                password=password
            )
        else:
            if not user.check_password(password):
                return http.HttpResponseBadRequest('绑定失败')
        OAuthQQUser.objects.create(user=user, openid=openid)
        login(request, user)

        response = redirect(reverse('contents:index'))

        response.set_cookie('username', user.username)

        return response


class WeiboAuthView(View):
    def get(self, request):
        next = request.GET.get('next')
        client = sinaweibopy3.APIClient(app_key=settings.APP_KEY, app_secret=settings.APP_SECRET,
                                        redirect_uri=settings.REDIRECT_URL)
        login_url = client.get_authorize_url()
        return JsonResponse({
            'code': RETCODE.OK,
            'errmsg': 'ok',
            'login_url': login_url})


class WeiboCallBackView(View):
    def get(self, request):
        code = request.GET.get('code')
        if code is None:
            return http.HttpResponseBadRequest('参数不全')
        client = sinaweibopy3.APIClient(app_key=settings.APP_KEY, app_secret=settings.APP_SECRET,
                                        redirect_uri=settings.REDIRECT_URL)
        result = client.request_access_token(code)
        client.set_access_token(result.access_token, result.expires_in)

        uid = result.uid
        try:
            weibouser = OAuthSinaUser.objects.get(uid=uid)
        except OAuthSinaUser.DoesNotExist:
            return render(request, 'sina_callback.html', context={'openid': uid})
        else:
            login(request, weibouser.user)
            response = redirect(reverse('contents:index'))
            response.set_cookie('username', weibouser.user.username)
        return response

    def post(self, request):
        mobile = request.POST.get('mobile')
        password = request.POST.get('pwd')
        uid = request.POST.get('openid')

        try:
            user = User.objects.get(mobile=mobile)
        except User.DoesNotExist:
            user = User.objects.create_user(
                username=mobile,
                mobile=mobile,
                password=password
            )
        else:
            if not user.check_password(password):
                return http.HttpResponseBadRequest('绑定失败')
        OAuthSinaUser.objects.create(user=user, uid=uid)
        login(request, user)

        response = redirect(reverse('contents:index'))

        response.set_cookie('username', user.username)

        return response
